package org.serg.match3;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class PlayerDAO {

	// Database fields
	  private SQLiteDatabase database;
	  public PlayerDAO(SQLiteDatabase database) {
		  this.database = database;
	  }

	  public UserModel createPlayer(String name) {
	    ContentValues values = new ContentValues();
	    values.put("name", name);
	    values.put("score", 0);
	    long insertId = database.insert("Players", null, values);
	    
	    Cursor cursor = database.
	    		  rawQuery("select * from Players where _id = ? ", 
	    				  new String[] { Long.toString(insertId) });
	    
	    if (!cursor.moveToFirst()) {
	    	return null;
	    }
	    UserModel user = cursorToPlayer(cursor);
	    cursor.close();
	    return user;
	  }

	  public UserModel getPlayer(long id) {
	    	Cursor cursor = database.
		    		  rawQuery("select * from Players where _id = ? ", 
		    				  new String[] { Long.toString(id) });
		    
		    if (!cursor.moveToFirst()) {
		    	return null;
		    }
		    UserModel user = cursorToPlayer(cursor);
		    cursor.close();
		    return user;
		}

	  public List<UserModel> getAllPlayers() {
	    List<UserModel> users = new ArrayList<UserModel>();

	    Cursor cursor = database.
	    		  rawQuery("select * from Players ", new String[] {});
	    
	    cursor.moveToFirst();
	    while (!cursor.isAfterLast()) {
	    	UserModel user = cursorToPlayer(cursor);
	    	users.add(user);
	      cursor.moveToNext();
	    }
	    // Make sure to close the cursor
	    cursor.close();
	    return users;
	  }
	  
	  public int updatePlayer(UserModel user) {
		    
		    ContentValues values = new ContentValues();
		    values.put("name", user.getName());
		    values.put("score", user.getScore());
		 
		    // updating row
		    return database.
		    		update("Players", values, "_id = ?",
		            new String[] { String.valueOf(user.getId()) });
		}
	  
	  public void deletePlayer(UserModel user) {
		    long id = user.getId();
		    System.out.println("Player deleted with id: " + id);
		    database.delete("Players", "_id = " + id, null);
		  }

	  private UserModel cursorToPlayer(Cursor cursor) {
		UserModel user = new UserModel();
		user.setId(cursor.getLong(0));
		user.setName(cursor.getString(1));
		user.setScore(cursor.getInt(2));
		return user;
	  }
}
